package com.yk.framework.gui.core;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.yk.framework.gui.core.impl.CoreUI;
import com.yk.framework.gui.ctrl.YKTabbedPane;
import com.yk.framework.gui.ctrl.YKTabbedPane.CloseTabListener;
import com.yk.framework.gui.login.panel.MainFrame;

/**
 * @author lifetime
 * 
 */
public class UIInstanceManager implements CloseTabListener, ChangeListener {
	List<CoreUI> uiList;
	YKTabbedPane uiContain;
	static UIInstanceManager instance;
	CoreUI currentCoreUI;
	MainFrame mainFrame;

	private UIInstanceManager(MainFrame mainFrame) {
		uiList = new ArrayList<CoreUI>();
		this.mainFrame = mainFrame;
		this.uiContain = mainFrame.getUiContain();
		uiContain.addChangeListener(this);
		uiContain.setCloseTabListener(this);
	}

	public void stateChanged(ChangeEvent e) {
		CoreUI coreUI = (CoreUI) uiContain.getSelectedComponent();
		if (coreUI != null) {
			changeSelected(coreUI);
		}
	}

	public static synchronized void init(MainFrame mainFrame) {
		if (instance == null) {
			instance = new UIInstanceManager(mainFrame);
		}
	}

	public boolean exists(String uiName, boolean isChange) {
		for (int i = 0; i < uiList.size(); i++) {
			if (uiName.equals(uiList.get(i).getClass().getName())) {
				if (isChange) {
					CoreUI ui = uiList.get(i);
					changeSelected(ui);
				}
				return true;
			}
		}
		return false;
	}

	public static UIInstanceManager getThis() {
		return instance;
	}

	public synchronized void add(CoreUI coreUI) {
		uiContain.add(coreUI.getUITitle(), coreUI);
		uiList.add(coreUI);
		currentCoreUI = coreUI;
		changeSelected(coreUI);
	}

	public void changeSelected(CoreUI coreUI) {
		uiContain.setSelectedComponent(coreUI);
		mainFrame.changeUIToolBar(coreUI);
		uiContain.validate();
		uiContain.doLayout();
	}

	public CoreUI getCurrentActiveUI() {
		return currentCoreUI;
	}

	public void click(int index) {

	}

	public boolean isCancel() {
		return false;
	}

	public synchronized void removeAfter(int index) {
		int i = 0;
		for (Iterator<CoreUI> it = uiList.iterator(); it.hasNext(); i++) {
			it.next();
			if (index == i) {
				it.remove();
			}
		}
		mainFrame.resetUIToolBar();
		if (uiList.size() > 0) {
			CoreUI ui = uiList.get(uiList.size() - 1);
			mainFrame.changeUIToolBar(ui);
		}
	}
}
